package top.zywork.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import top.zywork.annotation.ContentSecCheck;
import top.zywork.enums.SecCheckTypeEnum;
import top.zywork.service.ContentSecCheckService;
import top.zywork.vo.BaseVO;
import top.zywork.vo.ResponseStatusVO;

/**
 * 在controller方法中指定@ContentSecCheck注解后，可对用户提交数据进行检测<br />
 * 创建于2020-02-26<br/>
 *
 * @author 王振宇
 * @version 1.0
 */
@Component
@Aspect
@Slf4j
public class ContentSecCheckAspect {

    private ContentSecCheckService contentSecCheckService;

    @Pointcut("@annotation(top.zywork.annotation.ContentSecCheck)")
    public void methodAspect() {}

    @Around("methodAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("start to check the content...");
        Object[] argsArray = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ContentSecCheck contentSecCheck = signature.getMethod().getDeclaredAnnotation(ContentSecCheck.class);
        if (contentSecCheck.checkType() == SecCheckTypeEnum.TEXT && contentSecCheck.isJson()) {
            for (Object args : argsArray) {
                if (args instanceof BaseVO) {
                    if (!contentSecCheckService.checkText(JSON.toJSONString(args))) {
                        return ResponseStatusVO.dataError("文字内容审核未通过", null);
                    }
                }
            }
        } else if (contentSecCheck.checkType() == SecCheckTypeEnum.TEXT && !contentSecCheck.isJson()) {
            StringBuilder allStr = new StringBuilder();
            for (Object args : argsArray) {
                if (args instanceof String) {
                    allStr.append(args);
                }
            }
            if (!contentSecCheckService.checkText(JSON.toJSONString(allStr))) {
                return ResponseStatusVO.dataError("文字内容审核未通过", null);
            }
        } else if (contentSecCheck.checkType() == SecCheckTypeEnum.IMAGE) {
            for (Object args : argsArray) {
                if (args instanceof MultipartFile) {
                    if (!contentSecCheckService.checkImage((MultipartFile) args)) {
                        return ResponseStatusVO.dataError("图片内容审核未通过", null);
                    }
                }
            }
        }
        return joinPoint.proceed();
    }

    @Autowired
    public void setContentSecCheckService(ContentSecCheckService contentSecCheckService) {
        this.contentSecCheckService = contentSecCheckService;
    }
}